/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.fraclite.adl;

import java.util.HashMap;

import org.objectweb.fractal.adl.Factory;
import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.util.Fractal;

/**
 * A class to launch a component from its definition from the command line.
 * Usage:
 * Launcher [-java|-fractal] &lt;definition&gt; [ &lt;itf&gt; ]
 * where &lt;definition&gt; is the name of the component to be instantiated 
 * and started,and &lt;itf&gt; is the name of its Runnable interface, if it 
 * has one.
 */

public class Launcher {

  private Launcher () {
  }

  public static void main (final String[] args) throws Exception {
    String[] pargs = parseArgs(args);
    
    Factory f = FactoryFactory.getFactory(FactoryFactory.FRACLITE_FACTORY, FactoryFactory.FRACLITE_BACKEND, new HashMap<String, Object>());
    Component apps = (Component)f.newComponent(pargs[0], new HashMap<String, Object>());

    try {
      Fractal.getLifeCycleController((Component)apps).startFc();
    } catch (NoSuchInterfaceException ignored) { }

    try {
      Runnable r = (Runnable)((Component)apps).getFcInterface(pargs[1]);
      r.run();
    } catch (NoSuchInterfaceException ignored) { }
         
  }
  
  private static String[] parseArgs (final String[] args) {
    if (args.length < 1 || args.length > 2) {
      parseError();
    }
    String[] result = new String[2];
    result[0] = args[0];
    result[1] = args.length == 2 ? args[1] : "run";
    return result;
  }
  
  private static void parseError () {
    System.out.println("Usage: Launcher <definition> [ <itf> ]");
    System.out.print("where <definition> is the name of the component to be ");
    System.out.print("instantiated and started,\nand <itf> is the name of ");
    System.out.println("its Runnable interface, if it has one");
    System.exit(1);
  }
}
